package cn.yi.newsys.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.yi.newsys.listener.UserActiveListener;
import cn.yi.newsys.pojo.User;
import cn.yi.newsys.service.UserService;
import cn.yi.newsys.service.impl.UserServiceImpl;

public class UserServlet extends HttpServlet {


	private static final long serialVersionUID = 1L;
	private String charEncoding = "UTF-8" ;

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 将所有请求都交给 doPost 处理
		this.doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应的类型
		// charset=UTF-8 用来设置字符编码格式，如不添加，则无法输出中文
		response.setContentType("text/html;charset="+charEncoding);
  		// 接收处理的参数
  		String action = request.getParameter("action");

  		if(action != null && action.length() > 0){
  			if(action.equals("reg")){
  				this.doReg(request, response) ;
  			}else if(action.equals("login")){
  				this.doLogin(request, response) ;
  			}else if(action.equals("out")){
  				this.out(request, response) ;
  			}
  		}
			

	}


	@Override
	public void init(ServletConfig config) throws ServletException {
		charEncoding = config.getInitParameter("charEncoding") ;
	}


	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 * 注册
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doReg (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

		PrintWriter out = response.getWriter();
		String userName = request.getParameter("userName") ;
  		String userPass = request.getParameter("userPwd") ;
  		String email = request.getParameter("email") ;
  		String userType = request.getParameter("userType") ;
  		// 将用户提交的数据封装成 User 对象
		User user = null ;
  		if(userType != null && userType.length() > 0){
  			user = new User(userName,userPass,1,email) ;
  			user.setType(Integer.valueOf(userType)) ;
  		}else{
  			user = new User(userName,userPass,1,email) ;
  		}
		// 添加业务逻辑层的引用
		UserService userService = new UserServiceImpl() ;
		int num = userService.registerUser(user) ;
		if(num == 1){
			// 注册成功
			out.println("<script>alert('注册成功！');location.href='index.jsp';</script>") ;
		}else if(num == 0){
			// 注册失败
			out.println("<script>alert('注册失败！');location.href='index.jsp';</script>") ;
		}else if(num == -1){
			// 用户名被占用
			out.println("<script>alert('用户名已存在！');location.href='index.jsp';</script>") ;
		}
		// 刷新流
		out.flush() ;
		// 关闭流
		out.close() ;
		
	}
	
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	private void doLogin (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession() ;
		String userName = request.getParameter("userName") ;
		String userPass = request.getParameter("userPwd") ;
		// 创建 User 对象
		User user = new User(userName,userPass) ;
		// 创建用于业务逻辑类对象
		UserService us = new UserServiceImpl() ;
		// 处理业务，并接收返回值
		User temp = us.login(user) ;
		if(temp != null){
			// 登录成功			
			// 保存用户的登录状态
			session.setAttribute("User", temp) ;
			
			// 绑定在线人数监听器
			UserActiveListener listener = new UserActiveListener() ;
			session.setAttribute("userActive", listener) ;
			// 判断用户类型
			if(temp.getType() == 1){
				// 保存用户状态
				// 获取用户名和密码
				String code = user.getUserName()+"&"+user.getUserPass() ;
				// 重新编码
				code = URLEncoder.encode(code, "UTF-8") ;
				// 创建 Cookie 对象
				Cookie cookie = new Cookie("code",code);
				// 设置 Cookie 的有效期，十天内免登陆
				cookie.setMaxAge(60*60*24*10) ;
				// 有效路径
				cookie.setPath("/") ;
				// 由服务器向客户端写入 Cookie
				response.addCookie(cookie) ;
				// 重定向回首页
				response.sendRedirect("index.jsp") ;
			}else{
				// 管理员
				// 设置 session 有效期，以秒为单位
				session.setMaxInactiveInterval(60*60*24*10) ;
				response.sendRedirect("manage/index.jsp");
			}
		}else{
			// 登录失败
			out.println("<script>alert('登陆失败！') ;location.href='index.jsp';</script>") ;
		}
	}
	
	/**
	 * 注销
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void out(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		PrintWriter out = response.getWriter() ;
		// 获取当前请求的 session
		HttpSession session = request.getSession() ;
		// 设置会话失效
		session.removeAttribute("User") ;
		session.removeAttribute("userActive") ;
		// 创建 cookie对象
		Cookie cookie = new Cookie("code", null) ;
		// 设置 cookie 的有效时间，0 代表永远生效
		cookie.setMaxAge(0) ;
		// 设置cookie 有效路径，根目录生效
		cookie.setPath("/") ;
		// 由服务端发送 cookie 
		response.addCookie(cookie) ;
		// 重定向回首页
		response.sendRedirect("index.jsp") ;
	}
}
